package jyl.pdfbox;

import jyl.pdfbox.bean.PdfPhrase;
import jyl.pdfbox.bean.PdfRow;

import org.apache.pdfbox.util.TextPosition;

/**
 * 类描述：   
 * 创建人：jinyongliang
 * 创建时间：2012-1-16 下午10:33:33   
 * 修改人：jinyongliang   
 * 修改时间：2012-1-16 下午10:33:33   
 * 修改备注：   
 * @version 
 */
public class PdfTableExtractor {
	
	PdfRow lastRow ;
	PdfPhrase lastPhrase ;
	PdfRow currentRow ;
	PdfPhrase currentPhrase ;
	TextPosition lastTextPosition;
	private  static PdfTableExtractor instance =   new PdfTableExtractor(); 
	public static PdfTableExtractor getInstance() {
		return instance;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	private PdfTableExtractor(){}
	/**
	 * @处理pdf文件的一个位置
	 */
	public void dealOneTP(TextPosition tp) {
		// TODO Auto-generated method stub
		if(tp.getCharacter().trim().equals(""))
			return;
//		System.out.println(tp.getCharacter()+":"+tp.getX()+":"+tp.getY());
		/*if(2>1)
			return;*/
		int compareResulst = compareTextPosition(tp);
		switch (compareResulst)
		{
		case 1:
			
			if(currentPhrase==null)
				currentPhrase = new PdfPhrase();
			currentPhrase.addTextPosition(lastTextPosition);
			break;
			
		case 2:
			if(currentPhrase!=null)
			currentPhrase.addTextPosition(lastTextPosition);
			if(currentRow == null)
				currentRow = new PdfRow();
			
			lastPhrase = currentPhrase ;
			
			currentRow.addPdfPhrase(lastPhrase);
			
			currentPhrase = null;
			break;
		case 3:
			if(currentPhrase!=null)
			currentPhrase.addTextPosition(lastTextPosition);
			lastPhrase = currentPhrase ;
			currentPhrase = null;
			if(currentRow==null)
				currentRow = new PdfRow();
			currentRow.addPdfPhrase(lastPhrase);
			if(currentRow!=null)
				System.out.println(currentRow.getString());
			lastRow = currentRow;
			currentRow = null;
			lastPhrase = currentPhrase ;
			
		//	if(lastRow!=null)
		//	System.out.println(lastRow.getString());
		}
			lastTextPosition = tp;
	}
	/**
	 * @param tp
	 * @return
	 */
	private int compareTextPosition(TextPosition tp) {
		// TODO Auto-generated method stub
		if(lastTextPosition==null)
		{
			return -1;
		}
		float height = lastTextPosition.getHeight()>tp.getHeight()?tp.getHeight():lastTextPosition.getHeight();
		float width = lastTextPosition.getWidth()<tp.getWidth()?tp.getWidth():lastTextPosition.getWidth();
		float intervalWidth = width/2*3;
		float intervalHeight = height/10;
		float xInterval = tp.getX()-lastTextPosition.getX();
		float yInterval =  tp.getY()-lastTextPosition.getY();
		if(xInterval>0&&xInterval<intervalWidth&&yInterval<intervalHeight&&yInterval>=0)
		{//属于同一字符串
			return 1;
		}
		
		if(xInterval>0&&xInterval>intervalWidth&&yInterval<intervalHeight&&yInterval>=0)
		{//属于同一行,但不同字符串
			return 2;
		}
		
		if((xInterval<0||yInterval>=height))
		{//换行TODO 逻辑关系还需修改
			return 3;
		}
		return -1;
	}

}
